package api

import (
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"log"
	"math/rand"
	"net/http"
	"strconv"
	"time"
	"week-three/global"
	"week-three/internal/model/service"
	"week-three/internal/pkg"
	"week-three/internal/request"
)

func SendSms(c *gin.Context) {
	mobile := c.PostForm("mobile")

	if mobile == "" {
		c.JSON(http.StatusBadRequest, gin.H{"message": "手机号格式不能为空"})
		return
	}
	code := rand.Intn(9000) + 1000
	sms, err := pkg.SendSms(mobile, strconv.Itoa(code))
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err})
		return
	}
	//短信发送成功存入Redis里面
	global.Rdb.Set("sendSms", code, time.Minute*5)
	log.Println(sms.Body.Message)
	c.JSON(http.StatusOK, gin.H{"message": "成功", "data": code})
}

func Login(c *gin.Context) {
	var userReq request.UserRequest
	err := c.ShouldBind(&userReq)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"message": "参数获取失败"})
		return
	}
	//查询手机号是否存在
	user, _ := service.CheckUserByMobile(userReq.Mobile)
	if user.ID == 0 {
		c.JSON(http.StatusOK, gin.H{"message": "手机号不存在"})
		return
	}
	get := global.Rdb.Get("sendSms")
	if get.Val() != userReq.Code {
		c.JSON(http.StatusInternalServerError, gin.H{"message": "验证码错误"})
		return
	}
	//声明一个JWT结构体
	claims := pkg.CustomClaims{
		ID:     user.ID,
		Mobile: user.Mobile,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: global.GlobalConfig.Jwt.ExpiresAt,
		}}
	//实例化jwt
	newJWT := pkg.NewJWT(global.GlobalConfig.Jwt.Key)
	//生成token
	token, err := newJWT.CreateToken(claims)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"message": "token生成失败"})
		return
	}
	c.JSON(http.StatusOK, gin.H{"code": 200, "message": "成功", "token": token, "data": user.Mobile})

}
